package com.zyt.mall.product.web;

import com.zyt.mall.product.entity.CategoryEntity;
import com.zyt.mall.product.service.CategoryService;
import com.zyt.mall.product.vo.Catelog2Vo;
import org.redisson.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;

@Controller
public class IndexController {
    @Autowired
    CategoryService categoryService;
    @Autowired
    RedissonClient redisson;

    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @GetMapping({"/","/index.html"})
    public String indexPage(Model model) {
        //查出所有一级分类
        List<CategoryEntity> categoryEntities = categoryService.getLevel1Categorys();

        model.addAttribute("categorys",categoryEntities);
        return "index";
    }
    @ResponseBody
    @GetMapping("/index/catalog.json")
    public Map<String,List<Catelog2Vo>> getCatalogJson(){
        Map<String,List<Catelog2Vo>> catalogJson = categoryService.getCatalogJson();
        return catalogJson;
    }

    @ResponseBody
    @GetMapping("/hello")
    public String hello(){
        //1.获取一把锁只要锁的名字一样就是同一把锁
        RLock myLock = redisson.getLock("my_lock");
        //加锁
        //myLock.lock();//阻塞式等待,默认加的锁都是30s有效期，可以手动设置
        //锁的自动续期，如果业务超长，运行期间自动给锁续上新的30s，不用担心业务时间长，锁自动过期被删掉
        //加锁的业务只要运行完成，就不会给当前锁续期，即使不手动解锁，锁默认在30s以后自动删除

        myLock.lock(30, TimeUnit.SECONDS);//10秒以后自动解锁，自动解锁时间一定要大于业务执行时间
        //myLock.lock(10, TimeUnit.SECONDS);在锁时间到了以后不会自动续期
        //如果传递了锁的超时时间，就发送给redis执行脚本，进行占锁，默认超时就是我们指定的时间
        //如果未指定锁的超时时间，就使用30*1000【LockWatchdogTimeout看门狗的默认时间】
        //只要占领成功，就会启动一个定时任务【重新给锁设置过期时间，新的过期时间就是看门狗默认的时间】每隔十秒都会再次续期，续成30s
        //internalLockWatchdogTimeout【看门狗时间】、3、10s

        //最佳实战
        //myLock.lock(10, TimeUnit.SECONDS);省掉了整个续期操作.手动解锁
        try {
            System.out.println("加锁成功，执行业务..."+Thread.currentThread().getId());
            Thread.sleep(30000);
        } catch (Exception e) {

        }finally {
            System.out.println("释放锁..."+Thread.currentThread().getId());
            myLock.unlock();
        }
        return "hello";
    }


    //保证一定能读到最新数据，修改期间，写锁是一个排他锁（互斥锁、独享锁）读锁是一个共享锁
    //写锁没释放就必须等待
    //读+读 相当于无锁，并发读，只会在redis中记录，所有当前的读锁。他们都会同时加锁成功
    //写+读 等待写释放
    //写加写 阻塞方式
    //读+写  有读锁。写也要等待
    //只要有写的存在，都必须等待
    @GetMapping("/write")
    @ResponseBody

    public String writeValue(){
        RReadWriteLock lock = redisson.getReadWriteLock("rw-lock");
        String s = "";
        RLock rLock = lock.writeLock();
        try {
            rLock.lock();
            //改数据加写锁，读数据加读锁
            System.out.println("写锁加锁成功..."+Thread.currentThread().getId());
            s=UUID.randomUUID().toString();
            Thread.sleep(30000);
            stringRedisTemplate.opsForValue().set("writeValue",s);
        } catch (InterruptedException e) {
           e.printStackTrace();
        }finally {
            rLock.unlock();
            System.out.println("写锁释放成功..."+Thread.currentThread().getId());
        }
        return s;
    }
    @GetMapping("/read")
    @ResponseBody

    public String readValue(){
        RReadWriteLock lock = redisson.getReadWriteLock("rw-lock");
        //ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();
        String s = "";
        //加读锁
        RLock rLock = lock.readLock();
        rLock.lock();
        try {
            System.out.println("读锁加锁成功..."+Thread.currentThread().getId());
            s= stringRedisTemplate.opsForValue().get("writeValue");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            rLock.unlock();
            System.out.println("读锁释放成功..."+Thread.currentThread().getId());
        }
        return s;
    }

    @GetMapping("/park")
    @ResponseBody
    public String park() throws InterruptedException {
        RSemaphore park = redisson.getSemaphore("park");
        //park.acquire();//获取一个信号，获取一个值，占一个车位
        boolean b = park.tryAcquire();
        if(b){
            //执行业务
        }else {
            return "error";
        }
        return "ok=>"+b;
    }
    @GetMapping("/go")
    @ResponseBody
    public String go() throws InterruptedException {
        RSemaphore park = redisson.getSemaphore("park");
        park.release();//释放一个车位

//        Semaphore semaphore = new Semaphore(3);
//        semaphore.acquire();//获取一个信号，获取一个值，占一个车位
//        semaphore.release();//释放一个车位
        return "ok";
    }

    @GetMapping("/lockDoor")
    @ResponseBody
    public String lockDoor() throws InterruptedException {
        RCountDownLatch door = redisson.getCountDownLatch("door");
        door.trySetCount(5);
        door.await();
        return "放假了...";
    }
    @GetMapping("/gogogo/{id}")
    @ResponseBody
    public String gogogo(@PathVariable("id") Long id){
        RCountDownLatch door = redisson.getCountDownLatch("door");
        door.countDown();//计数减一
        return id+"班的人都走了...";
    }
}
